using SqlSugar;
using IM.Easy.Core.Services;
using IM.Easy.Core.Utils;
using IM.Easy.Infrastructure.Query;
using IM.Easy.Core.Extensions;
using IM.Easy.Entity.System;
using IM.Easy.SystemServices.Dtos;
using IM.Easy.SystemServices.IServices;

namespace IM.Easy.SystemServices.Services
{
    public class SysAccountSecurityService : AppServices<SysAccountSecurity>, ISysAccountSecurityService
    {

        public SysAccountSecurityService(ISqlSugarClient db) : base(db)
        {

        }

        public SysAccountSecurity Create(SysAccountSecurity entity)
        {
            // TODO: 添加创建逻辑
            return Context.Insertable(entity).ExecuteReturnEntity();
        }

        public SysAccountSecurity GetById(long id)
        {
            // TODO: 添加获取逻辑
            return Context.Queryable<SysAccountSecurity>().InSingle(id);
        }

        public PageResponse<SysAccountSecurity> GetPageList(SysAccountSecurityQueryDto query)
        {
            var queryable = Context.Queryable<SysAccountSecurity>();
            var exp = Expressionable.Create<SysAccountSecurity>();
            exp = exp
;
            var page = queryable
                 .Where(exp.ToExpression())
                 .ToPageList<SysAccountSecurity, SysAccountSecurity>(query);
            return page;
        }

        public bool Update(SysAccountSecurity entity)
        {
            // TODO: 添加更新逻辑
            return Context.Updateable(entity).ExecuteCommandHasChange();
        }

        public bool Delete(params long[] Id)
        {
            // TODO: 添加删除逻辑
            return Context.Deleteable<SysAccountSecurity>(Id).ExecuteCommandHasChange();
        }

        /// <summary>
        /// 解锁
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public bool UnLock(long userId)
        {
            var security = GetFirst(s => s.UserId == userId);
            security.IsLocked = false;
            security.FailedAttempts = 0;
            security.LastFailedAt = null;
            var flag = Update(security);
            return flag;
        }
    }
}
